package is.web;

import is.interfaces.Bean;
import java.util.LinkedList;

/**
 * Retrieve table
 *
 * @author aspr0
 */
public class Rtable
{
    public static String generate(Bean bean, LinkedList<String> linkTagrets, LinkedList<String> linkedValues,
                                  Integer... linkedFields)
    {
        String tableCanvas =
                "<table>"
                + "%s"
                + "</table>";

        String rowCanvas =
                "<tr>"
                + "<td class=\"rPadding\">%s</td>"
                + "<td>%s</td>"
                + "</tr>";

        String rows =
                "<tr>"
                + "<td>id</td>"
                + "<td>" + bean.getId() + "</td>"
                + "</tr>";

        String linkCanvas = "<a href=\"%sretrieve.jsp?id=%s\">%s</a>";

        for (int partNum = 0; partNum < bean.getFields().length; partNum++)
        {
            Boolean matchLinked = false;

            for (int linkedField : linkedFields)
            {
                if (partNum == linkedField)
                {
                    matchLinked = true;
                    break;
                }
            }

            String value;

            if (matchLinked)
            {
                if ("0".equals(bean.getValues()[partNum]))
                {
                    value = Locale.NULL;
                    linkedValues.removeFirst();
                    linkTagrets.removeFirst();
                }
                else
                {
                    value = String.format(linkCanvas, linkTagrets.removeFirst(), bean.getValues()[partNum],
                            linkedValues.removeFirst());
                }
            }
            else
            {
                value = bean.getValues()[partNum];
            }
            rows += String.format(rowCanvas, bean.getFields()[partNum], value);
        }

        return String.format(tableCanvas, rows);
    }
}
